#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import icu


def hsize(size, maxlen=5):
    __symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    idx = 0
    if size < 1000.0:
        return str(size) + ' ' + __symbols[idx]

    size = float(size)
    while size >= 1000.0:
        size /= 1024.0
        idx += 1

    if int(size) < 10: p1 = 1
    elif int(size) < 100: p1 = 2
    else: p1 = 3
    return '%*.*f %s' % (p1, maxlen - p1, size, __symbols[idx])


def get_encoding(text, encoding='auto'):
    enc = encoding
    dec = 'cp437'
    # noinspection PyBroadException
    try:
        text = text.encode(dec)
    except:
        dec = 'utf-8'
        text = text.encode(dec)

    if encoding == 'auto':
        enc = icu.CharsetDetector(text).detect().getName()
        # self.ENCODING = chardet.detect(names)['encoding']

    return enc, dec


def get_filename_folder(filename):
    __exts = ['.zip', '.rar', '.tar.gz', '.tar.bz2', '.tgz', '.tbz', '.tbz2', '.tar']
    p, fn = os.path.split(filename)
    fn, e1 = os.path.splitext(fn)
    fn, e2 = os.path.splitext(fn)
    if e2.lower() in __exts:
        return fn + os.path.sep
    else:
        return fn + e2 + os.path.sep


def get_intelligent_folder(filename, namelist):
    items = []
    for name in namelist.split('\n'):
        name = os.path.normpath(name)
        name = name.split('\\', 1)[0]
        itm = name.split('/', 1)[0]
        if itm not in items:
            items.append(itm)

    if len(items) == 1: return ''
    return get_filename_folder(filename)


def get_folder_and_file_names(folder):
    for (folder, dir_names, file_names) in os.walk(folder):
        dir_names.sort()
        file_names.sort()
        return dir_names, file_names


def get_folder_and_file_list(folder, recurse=False):
    file_list = []
    dir_list = []
    if os.path.isfile(folder): file_list.append(folder)
    for (folder, dir_names, file_names) in os.walk(folder):
        for d in dir_names:
            dir_list.append(os.path.relpath(folder + '/' + d))
        for f in file_names:
            file_list.append(os.path.relpath(folder + '/' + f))
        if not recurse: break
    file_list.sort()
    dir_list.sort()
    return dir_list, file_list


def get_diff_folder(files):
    if len(files) < 1: return ''
    s = files[0]
    pl = list(s.split(os.path.sep))
    s = ''
    for d in files:
        d = os.path.dirname(d)
        ffl = list(d.split(os.path.sep))
        l = min(len(ffl), len(pl))
        for i in range(l):
            if ffl[i] == pl[i]: s = os.path.sep.join(pl[:i+1])
            else: break
        pl = list(s.split(os.path.sep))
        s = ''
    return os.path.sep.join(pl) + '/'

